package com.sparkseries.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import reactor.core.publisher.Mono;

/**
 * Gateway限流
 * 自定义KeyResolver 基于Redis 为每个请求生成唯一的限制键
 * TODO 简化使用问题待解决
 */
@Configuration
public class RateLimitConfiguration {

    /**
     * 通过IP限流
     * @return
     */
    @Bean
    @Primary
    public KeyResolver  ipKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
    }

    /**
     * 通过用户ID限流
     * TODO 后期可更改为通过Token限流
     * @return
     */
    @Bean
    public KeyResolver  userKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("userId"));
    }

    /**
     * 通过接口限流
     * @return
     */
    @Bean
    public KeyResolver  apiKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getPath().value());
    }
}
